/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import React, { useState, useEffect, useRef } from "react";

export const PageTitle = (): React.ReactElement => {
    const [state, setState] = useState({
        noConnection: false,
        lightShown: false,
        info: null,
        lastSuccess: Date.now(),
        modalShown: false,
        errorText: null,
    });

    const timeoutId = useRef<number | null>(null);

    const refreshLoop = () => {
        clearTimeout(timeoutId.current);
        fetch("/v1/info")
            .then((response) => response.json())
            .then((info) => {
                setState((prevState) => ({
                    ...prevState,
                    info: info,
                    noConnection: false,
                    lastSuccess: Date.now(),
                    modalShown: false,
                }));
                $("#no-connection-modal").hide();
                resetTimer();
            })
            .catch((error) => {
                setState((prevState) => ({
                    ...prevState,
                    noConnection: true,
                    lightShown: !prevState.lightShown,
                    errorText: error,
                }));
                resetTimer();

                if (!state.modalShown && (error || Date.now() - state.lastSuccess > 30 * 1000)) {
                    $("#no-connection-modal").hide();
                    setState((prevState) => ({ ...prevState, modalShown: true }));
                }
            });
    };

    const resetTimer = () => {
        clearTimeout(timeoutId.current);
        timeoutId.current = window.setTimeout(refreshLoop, 1000);
    };

    useEffect(() => {
        refreshLoop();

        return () => {
            clearTimeout(timeoutId.current);
        };
    }, []);

    const { info } = state;
    if (!info) {
        return null;
    }

    return (
        <div>
            <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
                <div className="container-fluid">
                    <div className="navbar-header">
                        <table>
                            <tbody>
                                <tr>
                                    <td>
                                        <a href="/ui/">
                                            <img src="assets/logo.png" />
                                        </a>
                                    </td>
                                    <td>
                                        <span className="navbar-brand">Presto Router Overview</span>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <button
                        className="navbar-toggler"
                        type="button"
                        data-bs-toggle="collapse"
                        data-bs-target="#navbar"
                        aria-controls="navbar"
                        aria-expanded="false"
                        aria-label="Toggle navigation"
                    >
                        <span className="navbar-toggler-icon"></span>
                    </button>
                    <div id="navbar" className="navbar-collapse collapse">
                        <ul className="nav navbar-nav navbar-right">
                            <li>
                                <span className="navbar-cluster-info">
                                    <span className="uppercase">Environment</span>
                                    <br />
                                    <span className="text" id="environment">
                                        {info.environment}
                                    </span>
                                </span>
                            </li>
                            <li>
                                <span className="navbar-cluster-info logout">
                                    <a className="btn btn-md btn-info style-check logout-btn" href="/logout">
                                        Logout
                                    </a>
                                </span>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
            <div id="no-connection-modal" className="modal" tabIndex={-1} role="dialog">
                <div className="modal-dialog modal-sm" role="document">
                    <div className="modal-content">
                        <div className="row error-message">
                            <div className="col-12">
                                <br />
                                <h4>Unable to connect to server</h4>
                                <p>{state.errorText ? "Error: " + state.errorText : null}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};
